package com.zrrd.aaa;

/**
 * @author WanJl
 * @version 1.0
 * @title TimeFormatter
 * @description
 * @create 2024/8/30
 */
public class TimeFormatter {
    public static String formatDuration(int seconds) {
        if (seconds == 0) return "now";

        int years = seconds / (365 * 24 * 3600);
        seconds %= (365 * 24 * 3600);
        int days = seconds / (24 * 3600);
        seconds %= (24 * 3600);
        int hours = seconds / 3600;
        seconds %= 3600;
        int minutes = seconds / 60;
        seconds %= 60;

        String[] parts = {
                years > 0 ? years + " year" + (years > 1 ? "s" : "") : "",
                days > 0 ? days + " day" + (days > 1 ? "s" : "") : "",
                hours > 0 ? hours + " hour" + (hours > 1 ? "s" : "") : "",
                minutes > 0 ? minutes + " minute" + (minutes > 1 ? "s" : "") : "",
                seconds > 0 ? seconds + " second" + (seconds > 1 ? "s" : "") : ""
        };

        String result = "";
        for (String part : parts) {
            if (!part.isEmpty()) {
                if (!result.isEmpty()) {
                    result += ", ";
                }
                result += part;
            }
        }

        int lastCommaIndex = result.lastIndexOf(", ");
        if (lastCommaIndex != -1) {
            result = result.substring(0, lastCommaIndex) + " and" + result.substring(lastCommaIndex + 1);
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(formatDuration(62));       // "1 minute and 2 seconds"
        System.out.println(formatDuration(3662));     // "1 hour, 1 minute and 2 seconds"
        System.out.println(formatDuration(0));        // "now"
        System.out.println(formatDuration(31536000)); // "1 year"
    }
}
